#include "front/front_interface.h"

using namespace std;
using namespace ppspeech;


// the first and the second words are all_tone_three
vector<pair<string, string>> FrontEngineInterface::MergeThreeTones(vector<pair<string, string>>& seg_result)
{
	vector<pair<string, string>> result;
	string word;
	string pos;
	vector<vector<string>> finals;  //韵母数组
	vector<string> word_final;
	vector<bool> merge_last(seg_result.size(), false);

	// 判断最后一个分词结果是不是标点，不看标点的声母韵母
	int word_num = seg_result.size() - 1;

	// seg_result[word_num].first
	if( find(mcPunctuation.begin(), mcPunctuation.end(), get<0>(seg_result[word_num])) == mcPunctuation.end() ) {  // 最后一个分词结果不是标点
		word_num += 1;
	}

	// 获取韵母数组
	for(int i = 0; i < word_num; i++) {
		word_final = {};
		word = get<0>(seg_result[i]);
		pos = get<1>(seg_result[i]);
		if( find(_punc_omit.begin(), _punc_omit.end(), word) == _punc_omit.end() ) {  // 非可忽略的标点，即文字
			if( 0 != GetFinals(word, &word_final) ) {
				printf("ERROR: Frontend: Failed to get the final of word.\n");
			}
		}

		finals.push_back(word_final);
	}
	assert(word_num == finals.size());

	// 对第三声读音的字词分词结果进行处理
	for(int i = 0; i < word_num; i++) {
		word = get<0>(seg_result[i]);
		pos = get<1>(seg_result[i]);

		if( i - 1 >= 0 && AllToneThree(finals[i - 1]) && AllToneThree(finals[i]) && !merge_last[i - 1] )
		{
			// if the last word is reduplication, not merge, because reduplication need to be _neural_sandhi seg_result[i - 1].first
			if (!IsReduplication(get<0>(seg_result[i - 1])) &&
				(ppspeech::utf8string2wstring(get<0>(seg_result[i - 1]))).length() + (ppspeech::utf8string2wstring(word)).length() <= 3)
			{
				result.back().first = result.back().first + get<0>(seg_result[i]);
				merge_last[i] = true;
			}
			else {
				result.push_back(make_pair(word, pos));
			}
		}
		else {
			result.push_back(make_pair(word, pos));
		}
	}

	//把标点的分词结果补上
	if (word_num < seg_result.size()) {
		result.push_back(
			// seg_result[word_num].first seg_result[word_num].second
			// get<0>((*seg_result)[word_num])
			make_pair( get<0>(seg_result[word_num]), get<1>(seg_result[word_num]) ));
	}

	return result;
}


// 根据韵母判断该词中每个字的读音都为第三声。true表示词中每个字都是第三声
bool FrontEngineInterface::AllToneThree(const vector<string> &finals)
{
	bool flags = true;
	if(finals.size() == 0) {
		return false;
	}

	for (int i = 0; i < finals.size(); i++) {
		if (static_cast<int>(finals[i].back()) != 51) {  //如果读音不为第三声
			flags = false;
		}
	}
	return flags;
}
